<?php

namespace app\index\controller;

use app\index\BaseController;
use app\common\model\BoardMessage;

class MessagesBoard extends BaseController
{
    /**
     * 查看留言板
     *
     * @return \think\Response
     * @args page? 页码
     */
    public function fetchBoardMessages()
    {
        return json(
            BoardMessage::with(['author'])
                ->order('create_at', 'desc')
                ->paginate(10)
        );
    }

    /**
     * 发布留言
     *
     * @return \think\Response
     * @args content 留言内容
     */
    public function createBoardMessage()
    {
        $this->validateOrError();

        $content = input('content');

        $user = getCurrentUser();
        $message = new BoardMessage();
        $message->author_id = $user->id;
        $message->content = $content;
        $message->save();

        return json([
            'message' => '留言成功'
        ]);
    }

    /**
     * 编辑留言
     *
     * @return \think\Response
     * @args id 留言ID
     * @args content 留言内容
     */
    public function editBoardMessage($id)
    {
        $this->validateOrError();

        $content = input('content');

        $user = getCurrentUser();

        /** @var BoardMessage $message */
        $message = BoardMessage::where('id', $id)->find();
        if (!$message) {
            error('留言不存在');
        }

        if ($message->author_id !== $user->id) {
            error('你不是此留言的作者，不能编辑');
        }

        $message->content = $content;
        $message->save();

        return json([
            'message' => '编辑成功'
        ]);
    }

    /**
     * 删除留言
     *
     * @return \think\Response
     * @args id ID
     */
    public function removeBoardMessage($id)
    {
        $user = getCurrentUser();

        /** @var BoardMessage $message */
        $message = BoardMessage::where('id', $id)->find();
        if (!$message) {
            error('留言不存在');
        }

        if ($message->author_id !== $user->id) {
            error('你不是此留言的作者，不能删除');
        }

        $message->delete();

        return json([
            'message' => '删除成功'
        ]);
    }
}
